Bash / Shell 終端色彩與字型樣式
參考資料
參考FLOZz’ MISC的說明頁面
1. 核心語法結構
控制碼的基本格式為:
\e[<樣式/顏色代碼>m
-
\e[(或\033[、\x1b[):CSI(Control Sequence Introducer)前綴。 -
<代碼>:樣式代碼,多個代碼可用分號;串接(例如\e[1;31;40m代表 粗體 + 紅字 + 黑底)。 -
m:Select Graphic Rendition(SGR)終止符號。 -
\e[0m:重置控制碼。若最後沒有重置,後續整個終端的文字都會被染成該顏色!
基本使用範例
# 使用 echo (需加上 -e)
echo -e "\e[1;31m[ERROR]\e[0m 伺服器連線失敗"
# 更加推薦的 POSIX 標準寫法 (printf,免 -e 且各平台完全通用)
printf "\033[1;32m[SUCCESS]\033[0m 部署完成\n"
2. 文字樣式控制 (Text Formatting)
Formatting
Set
| Code | Description | Example | Preview |
|---|---|---|---|
| 1 | Bold/Bright | echo -e "Normal \e[1mBold" | Normal Bold |
| 2 | Dim | echo -e "Normal \e[2mDim" | Normal Dim |
| 4 | Underlined | echo -e "Normal \e[4mUnderlined" | Normal Underlined |
| 5 | Blink 1) | echo -e "Normal \e[5mBlink" | Normal Blink |
| 7 | Reverse (invert the foreground and background colors) | echo -e "Normal \e[7minverted" | Normal inverted |
| 8 | Hidden (useful for passwords) | echo -e "Normal \e[8mHidden" | Normal Hidden |
Reset
8/16 colors
Foreground (text)
Background
4. 進階:256 色與 24-bit True Color (RGB)
現代終端機(如 iTerm2、Windows Terminal、Alacritty、Kitty)皆已支援更豐富的 256 色與 RGB 真彩色:
-
256 色模式:
-
前景:
\e[38;5;<0-255>m -
背景:
\e[48;5;<0-255>m -
範例:
echo -e "\e[38;5;208m這是漂亮的橘色\e[0m"
-
-
24-bit True Color (RGB):
-
前景:
\e[38;2;<R>;<G>;<B>m -
背景:
\e[48;2;<R>;<G>;<B>m -
範例:
echo -e "\e[38;2;255;100;0m自定義 RGB 珊瑚色\e[0m"
-
5. 工程師實戰:封裝易讀的日誌函式 (Script Boilerplate)
不要在 Shell Script 內散落難懂的 \e[31m。業界標準做法是在腳本開頭統一定義常數變數或封裝 Helper Function:
#!/bin/bash
# --- 定義色彩變數 ---
C_RESET="\033[0m"
C_BOLD="\033[1m"
C_RED="\033[1;31m"
C_GREEN="\033[1;32m"
C_YELLOW="\033[1;33m"
C_BLUE="\033[1;34m"
C_CYAN="\033[1;36m"
# --- 日誌函式 ---
log_info() {
printf "${C_BLUE}[INFO]${C_RESET} %s\n" "$*"
}
log_success() {
printf "${C_GREEN}[SUCCESS]${C_RESET} %s\n" "$*"
}
log_warn() {
printf "${C_YELLOW}[WARN]${C_RESET} %s\n" "$*"
}
log_error() {
printf "${C_RED}[ERROR]${C_RESET} %s\n" "$*" >&2
}
# --- 測試呼叫 ---
log_info "正在啟動 Docker Compose 服務..."
log_warn "記憶體剩餘不足 512MB"
log_success "Nextcloud 備份成功完成"
log_error "無法連接 MariaDB 資料庫"














































